package com.hjsmallfly.syllabus.repository.lesson

import com.hjsmallfly.syllabus.repository.lesson.local.LessonLocalDataSource
import com.hjsmallfly.syllabus.repository.lesson.remote.LessonRemoteDataSource
import com.hjsmallfly.syllabus.room.record.LessonRecord
import rx.Observable

class LessonDataRepository(
    private val localDataSource: LessonLocalDataSource,
    private val remoteDataSource: LessonRemoteDataSource
) : LessonDataSource {

    override fun saveLesson(lesson: LessonRecord) = localDataSource.saveLesson(lesson)

    override fun queryLessonDetail(cid: Long, isCache: Boolean): Observable<LessonRecord> {
        if (isCache) {
            return localDataSource.queryLessonDetail(cid, isCache)
        } else {
            return remoteDataSource.queryLessonDetail(cid, isCache)
                .doOnNext {
                    localDataSource.saveLesson(it).toBlocking().first()
                }
        }
    }
}